<template>
  <div class="login">
    <h3>登录</h3>
    <el-divider></el-divider>
    <el-input v-model="username" placeholder="请输入" class="mb">
      <template slot="prepend">用户</template>
    </el-input>
    <el-input type="password" v-model="password" placeholder="请输入" class="mb">
      <template slot="prepend">密码</template>
    </el-input>
    <div class="error">{{message}}</div>
    <el-button type="primary" @click="login">登录</el-button>
    <el-button @click="$router.push('/reg')">注册</el-button>
  </div> 
</template>
<script>
export default {
  data:()=>({
    username:'',
    password:'',
    message:''
  }),
  methods:{
    login(){
      let userinfo = {
          username:this.username,
          password:this.password
      }
      this.$axios({
        url:'/admin/acl/login',
        method:'post',
        data:userinfo
      }).then(
        res=>{
          if(res.data.success){
            //同步vuex && cookie
            // cookie.set('token', response.data.data.token, { domain: 'localhost' })
            this.$cookies.set('token',res.data.data.token)
            this.$store.commit('user/M_UPDATE_USER_TOKEN',
            {success: res.data.success,message:res.data.message,code:res.data.code,data:res.data.data})

            // 调用接口查询用户信息
            this.getUserInfo()

          }else{
            this.message=res.data.message
          }
        }
      )
    },
    getUserInfo(){
      this.$axios({
        url:'/admin/acl/index/info',
        method:'get',
        headers: {'token': this.$cookies.get('token')}
      }).then(
        res=>{
          if(res.data.success){
            //同步vuex && cookie
            // cookie.set('token', response.data.data.token, { domain: 'localhost' })
            this.$cookies.set('userInfo',res.data.data)
            this.$store.commit('user/M_UPDATE_USER_INFO',
            {success: res.data.success,code:res.data.code,message:res.data.message,data:res.data.data})

            if(!this.$route.query.path || /login|reg/.test(this.$route.query.path)){
              this.$router.replace('/user')
            }else{
              this.$router.replace(this.$route.query.path)
            }
          }else{
            this.message=res.data.message
          }
        }
      )
    },
  }
}
</script>

<style scoped>
.login{
  width:35%;
  height:auto;
  position: absolute;
  left:50%;top:50%;
  margin-left:-17%;
  transform: translateY(-50%)
}
.mb{
  margin-bottom: 20px;
}
.error{
  color:red
}
</style>
